from sc_engine.apps import messages as msgs
from sc_engine.apps.web.map_image_upload.transfer import image_download
from sc_engine.apps.web.map_image_upload.transfer import SFTPUpload
from sc_engine.apps.web.map_image_upload.transfer import FileCopy

err_msg = "Configuration file must specify 'upload_method' as 'copy' or 'sftp'"

def make_app(app_name, root_config, config):
    download = image_download

    upload_method = config['upload_method']

    if upload_method == 'copy':
        directory = config['directory']
        uploader = FileCopy(directory).copy
    elif upload_method == 'sftp':
        host = config['host']
        user = config['user']
        key_file = config['key_file']
        directory = config['directory']
        uploader = SFTPUpload(host, user, key_file, directory).upload
    else:
        raise KeyError(err_msg)

    app = MapImageUploadApp(download, uploader)

    return {
        msgs.MapFetchAnnouncement: app.map_fetch_announcement,
    }

class MapImageUploadApp(object):
    """Transfer map images from the kespa web site to the main site.

    Maps that are newly found will have their images downloaded, then uploaded
    to the web server of the main site.
    """
    def __init__(self, download, upload):
        self.download = download
        self.upload = upload

    def map_fetch_announcement(self, msg):
        map_id = msg.map_id
        filename = msg.image_filename

        map_filename = str(map_id) + '.jpg'
        image_data = self.download(filename)
        self.upload(map_filename, image_data)

